package com.xuanyuanxinyu.func.workmanager

import android.content.Context
import androidx.lifecycle.LifecycleOwner
import androidx.work.Constraints
import androidx.work.ExistingWorkPolicy
import androidx.work.OneTimeWorkRequest
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.WorkRequest
import androidx.work.Worker
import androidx.work.WorkerParameters
import java.util.concurrent.TimeUnit

/**
 * @FileName:
 * @Description:
 * @author ken.luo
 * @date 2023/4/4
 * @version V1.0
 * @email 424533553@qq.com
 */
class MyWorkManager {
    /**
     * 执行有条件限制的循环任务
     * 创建可循环的Work,最小的执行间隔是15min分钟
     */
    private fun createWork(context : Context) { //
        // 在充电情况下
        val constraints = Constraints.Builder().setRequiresCharging(true).build()
        val work = PeriodicWorkRequestBuilder<MyPeriodicWork>(1,TimeUnit.HOURS).build()
        val workManager = WorkManager.getInstance(context)
        workManager.enqueue(work)
       
    }
    
    
    private fun createPeriodicWork(context : Context) {
        // 周期任务

        val oneTimeWorkRequest : OneTimeWorkRequest? = null
        WorkManager.getInstance(context).enqueueUniqueWork(
            "sendLogs",ExistingWorkPolicy.KEEP,
            oneTimeWorkRequest!!
        )
    }
    
    /**
     * 按顺序执行任务,将任务串行起来
     */
    private fun workByOrder(context : Context){
        val workManager = WorkManager.getInstance(context)
        val uploadWorkRequest : OneTimeWorkRequest = OneTimeWorkRequestBuilder<MyPeriodicWork>().build()
        workManager.beginWith(uploadWorkRequest).then(uploadWorkRequest).enqueue()
        
    }
    
    /**
     * 可以指定一个弹性的周期任务
     */
    private fun createMinWork() {
        val work = PeriodicWorkRequestBuilder<MyPeriodicWork>(1,TimeUnit.HOURS,15,TimeUnit.MINUTES).build()
        
    }
    
    
    private fun funDemo(context : Context,owner : LifecycleOwner) {
        val workManager = WorkManager.getInstance(context)
        val workRequest : WorkRequest? = null
        //观察任务状态
        workManager.getWorkInfoByIdLiveData(workRequest!!.id).observe(
            owner
        ) { workInfo : WorkInfo?-> }
        val oneTimeWorkRequest : OneTimeWorkRequest? = null
        workManager.cancelWorkById(workRequest!!.id)
        val sets : List<String> = ArrayList(
            oneTimeWorkRequest!!.tags
        )
        workManager.cancelAllWorkByTag(sets[0])
    }
    
}

class MyPeriodicWork(context : Context,workerParams : WorkerParameters) : Worker(context,workerParams) {
    override fun doWork() : Result {
        return Result.success()
    }
}